//
//  EnjoyViewController.m
//  TasteEnjoy
//
//  Created by XuRui on 16/4/19.
//  Copyright © 2016年 XuRui. All rights reserved.
//

#import "EnjoyViewController.h"
#import "AFReachability.h"

#warning  1.Enjoy: TableView Tao collection
//轮播图:在tableHeaderView上


@interface EnjoyViewController ()<UITableViewDataSource, UITableViewDelegate, NewSelectDelegate, HotSelectDelegate, TuiJianSelectDelegate>
@property (nonatomic, retain) BaseTableView *tableView; /**< tabbleView 套 collection */

@property (nonatomic, retain) XrLunBoTu *viewLunbo; /**< 轮播view */

@property (nonatomic, retain) NSMutableArray *arrLunbo; /**< 轮播 arr */
@property (nonatomic, retain) NSMutableArray *arrLunboSelect; /**< 轮播点击 arr */

@property (nonatomic, retain) NSMutableArray *arrSort; /**< 分类 arr */
@property (nonatomic, retain) NSMutableArray *arrNew; /**< 新品 arr */
@property (nonatomic, retain) NSMutableArray *arrHot; /**< 热卖 arr */
@property (nonatomic, retain) NSMutableArray *arrTuiJian; /**< 推荐 arr */

@property (nonatomic, assign) NSInteger page;/**< 用来保存请求新数据动态值 */

@end

@implementation EnjoyViewController

#pragma mark - ------------ 内存管理 ---------------
- (void)dealloc
{
    [_tableView release];
    [_viewLunbo release];
    
    [_arrLunbo release];
    [_arrLunboSelect release];
    
    [_arrSort release];
    [_arrNew release];
    [_arrHot release];
    [_arrTuiJian release];
/** 防止野指针 */
    _tableView.delegate = nil;
    _tableView.dataSource = nil;
/** 移除通知 */
    [[NSNotificationCenter defaultCenter] removeObserver:self];

    [super dealloc];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"Enjoy";
    
    /** 打开数据库 */
    [[XrDataBaseManager shareInstace]openDataBase];
    [[XrDataBaseManager shareInstace]createTable];
     [AFReachability reachability];
    self.arrTuiJian = [NSMutableArray array];
    [self addSerVer];
    [self dataHandler];
    [self createTableView];
    [self refresh];
    
}

#pragma mark - ------------ 数据请求 ---------------

- (void)dataHandler
{

    
    [XrDataParse GETWithURL:@"https://open.seriousapps.cn/4/tab/list.json?city_id=1&lat=38.88341375456474&lng=121.5446097782637" par:nil success:^(id responseObject) {

        //轮播图
        self.arrLunbo = [NSMutableArray array];
        self.arrLunboSelect = [NSMutableArray array];
        NSArray *arrLunBo = responseObject[@"content"][0][@"data"][@"banner_list"];
        for (NSDictionary *dic in arrLunBo) {
            [_arrLunbo addObject:dic[@"img_url"]];
            [_arrLunboSelect addObject:dic[@"enjoy_url"]];
        }
        
        [self createLunbo];
        
        //分类
        NSArray *arrSORT = responseObject[@"content"][1][@"data"][@"group_list"];
        self.arrSort = [EnjoyModel modelHandleWithArrar:arrSORT];
        
        //新品
        NSArray *arrNEW = responseObject[@"content"][2][@"data"][@"product_list"];
        self.arrNew = [EnjoyModel modelHandleWithArrar:arrNEW];
        

        //热卖 判断
        NSArray *arr = responseObject[@"content"];
        if (arr.count == 4) {
            
          NSArray *arrHot = responseObject[@"content"][3][@"data"][@"product_list"];
            
          self.arrHot = [EnjoyModel modelHandleWithArrar:arrHot];
        }
        
        [self.tableView reloadData];
        
        
    } filed:^(NSError *error) {
    
    }];

     //推荐
  
    NSString *url = [NSString stringWithFormat:@"https://open.seriousapps.cn/4/tab/product.json?city_id=1&lat=38.88348548337112&lng=121.5446374387156&page=%ld", _page];
    
    [XrDataParse GETWithURL:url par:nil success:^(id responseObject) {
   
        NSArray *arrTuijian = responseObject[@"content"];
        NSArray *arr = [EnjoyModel modelHandleWithArrar:arrTuijian];
        [_arrTuiJian addObjectsFromArray:arr];
        
        [self.tableView reloadData];
        
    } filed:^(NSError *error) {
        
    }];
   
}

#pragma mark - ------------ 上拉加载 下拉刷新 ---------------

- (void)refresh
{
    //刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
    
        _page = 0;
        //如果page为0 移除数组
        if (_page == 0) {
            
            [_arrTuiJian removeAllObjects];
        }
        
        [self dataHandler];
        [_tableView.mj_header endRefreshing];
    }];
    
    //加载
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page ++;
        [self dataHandler];
        [_tableView.mj_footer endRefreshing];
    }];

    
}



#pragma mark - ------------ 创建轮播图 并点击跳转  ---------------

- (void)createLunbo
{

   if (_arrLunbo.count != 0) {
        
    self.viewLunbo = [[XrLunBoTu alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200) imgArr:_arrLunbo selectImageBlock:^(NSInteger index) {
        NSLog(@"点击了轮播图第%ld张", index);
        
        EnjoyLunboSelectViewController *lunbo = [[EnjoyLunboSelectViewController alloc]init];
        lunbo.url = _arrLunboSelect[index];
        
        [self.navigationController pushViewController:lunbo animated:YES] ;
        
    }];
    self.tableView.tableHeaderView = _viewLunbo;
    [_viewLunbo release];
 }
}


#pragma mark - ------------ 创建Tableview ---------------
- (void)createTableView
{
    
    self.tableView = [[BaseTableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
/** 夜间 */
    _tableView.dk_backgroundColorPicker = DKColorWithColors([UIColor whiteColor],[UIColor grayColor]);
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //注册4个cell
    [_tableView registerClass:[SortTableViewCell class] forCellReuseIdentifier:@"sort"];
    [_tableView registerClass:[NewTableViewCell class] forCellReuseIdentifier:@"new"];
    [_tableView registerClass:[HotTableViewCell class] forCellReuseIdentifier:@"hot"];
    [_tableView registerClass:[TuiJianTableViewCell class] forCellReuseIdentifier:@"tuijian"];
    [_tableView release];
}


#pragma mark - ------------ 返回row个数 ---------------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  
    if (_arrHot != nil) {
        return 4;
    }else{
        return 3;
    }
}


#pragma mark - ------------ cell赋值 判断 两个 cell ---------------

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
 
    switch (indexPath.row) {
        case 0:
        {
             //分类
            SortTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"sort"];
            
            cell.arrSort = _arrSort; /**< 传进去 数组 */
        
            return cell;
            
            break;
        }
        case 1:
        {
            //新品
            NewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"new"];
            
            cell.delegate = self;
        
            cell.arrNew = _arrNew;
            
            return cell;
            
            break;
        }
       case 2:
        {
          //如果有热卖数组 进热卖cell 如果没有 进推荐cell
            if (_arrHot != nil) {
                
                HotTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"hot"];
                
                
                cell.delegate = self;
                cell.arrHot = _arrHot;
                
                return cell;
            }else{
            
                TuiJianTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tuijian"];
                
                cell.arrTuiJian = _arrTuiJian;
                cell.delegate = self;
                return cell;
            
            }
          
            break;
        }
            
        default:
        {
            //如果热卖有数组 进推荐cell 若没有 说明 推荐已经在 第三个item了 则至为空
            if (_arrHot != nil) {
                
                TuiJianTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tuijian"];
                
                cell.arrTuiJian = _arrTuiJian;
                cell.delegate = self;
                return cell;
            }else{
            
                return nil;
            }
            
            break;
        }
    }
    
    
}

#pragma mark - ------------ 返回高度 ---------------
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 0:
        {
            //分类
            return 300;
            
            break;
        }
        case 1:
        {
            
           //新品
            return 580;
            
            break;
        }
        case 2:
        {
            //热卖 如果有数组 反580高 如果没有 进推荐 反250 *
            
            if (_arrHot != nil) {
                
                
                return 580;
            }else{
                
                return 250 * (_arrTuiJian.count / 2) + 80;
            }
            
            break;
        }
            
        default:
        {
            //热卖 如果有数组 反250 * 如果没有 没有这个cell
            if (_arrHot != nil) {
                
                return 250 * (_arrTuiJian.count / 2) + 80;
            }else{
                
                return 0;
            }
            
            break;
        }
    }
}

#pragma mark - ------------ 通知中心分类点击 ---------------
- (void)addSerVer
{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sortDetail:) name:@"index" object:nil];
}

- (void)sortDetail:(NSNotification *)noti
{
    
    NSLog(@"点击第%@个分类item", noti.object);
    
    NSInteger num = [noti.object integerValue];
    
        
    ESortDetailViewController *detail = [[ESortDetailViewController alloc]init];

    CATransition *animation = [CATransition animation];
    animation.duration = 0.8f;
    [animation setType:@"rippleEffect"];
    [self.navigationController.view.layer addAnimation:animation forKey:nil];
    
    EnjoyModel *m = _arrSort[num];
    
    detail.strID = [m.enjoy_url substringWithRange:NSMakeRange(33, 6)];
    detail.NaviTitle = m.title;
    [self.navigationController pushViewController:detail animated:YES];
        
    [detail release];
}

#pragma mark - ------------ 新品 点击 传id ---------------

- (void)NewSeclect:(NSIndexPath *)index
{

    [self pushDetailVCArr:_arrNew index:index animationType:@"rippleEffect"];
}

#pragma mark - ------------ 热卖 点击 传id ---------------
- (void)HotSeclect:(NSIndexPath *)index
{

    [self pushDetailVCArr:_arrHot index:index animationType:@"rippleEffect"];
}

#pragma mark - ------------ 推荐 点击 传id ---------------
- (void)TuiJianSeclect:(NSIndexPath *)index
{
  
  [self pushDetailVCArr:_arrTuiJian index:index animationType:@"rippleEffect"];
}

#pragma mark - ------------ 多次调用传值的方法 ---------------
- (void)pushDetailVCArr:(NSArray *)arr index:(NSIndexPath *)indexPath animationType:(NSString *)type
{
    EWebViewController *detail = [[EWebViewController alloc]init];
    EnjoyModel *m = arr[indexPath.row];
    detail.DetailID = m.product_id;
    detail.model = m;
    
    //动画
    CATransition *animation = [CATransition animation];
    animation.duration = 0.8f;
    [animation setType:type];
    [self.navigationController.view.layer addAnimation:animation forKey:nil];

    [self.navigationController pushViewController:detail animated:YES];
    [detail release];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
